package com.huaao.micropolice.core.service.system.impl;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.huaao.micropolice.core.model.system.Dept;
import com.huaao.micropolice.core.model.system.Menu;
import com.huaao.micropolice.core.model.system.Menu_Dept;
import com.huaao.micropolice.core.model.system.Role;
import com.huaao.micropolice.core.repository.system.DeptDao;
import com.huaao.micropolice.core.repository.system.MenuDao;
import com.huaao.micropolice.core.repository.system.MenuDeptDao;
import com.huaao.micropolice.core.repository.system.RoleDao;
import com.huaao.micropolice.core.service.system.MenuDeptService;

@Service
public class MenuDeptServiceImpl implements MenuDeptService{
	
	@Autowired
	private MenuDeptDao menuDeptDao;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private MenuDao menuDao;
	@Autowired
	private DeptDao deptDao;
	
	@Override
	public Set<Dept> findDepts(Menu menu, Role role) {
		Set<Dept> depts = new HashSet<Dept>();
		Set<Menu_Dept> menuDepts = role.getMenuDepts();
		for(Menu_Dept md : menuDepts){
			if(md.getMenu().equals(menu)){
				depts.add(md.getDept());
			}
		}
		return depts;
	}

	@Override
	public Set<String> findDeptsIds(Menu menu, Role role) {
		Set<String> deptIds = new HashSet<String>();
		Set<Dept> depts = findDepts(menu,role);
		for(Dept d : depts){
			deptIds.add(d.getId());
		}
		return deptIds;
	}

	@Override
	@Transactional
	public void bind(String id, String menuId, String[] ckDepts) {
		Role role = roleDao.load(id);
		menuDeptDao.clearDept(role , menuId);
		Menu m = menuDao.load(menuId);
		for(String ckdept : ckDepts){
			if(!StringUtils.isBlank(ckdept)){
				Dept d = deptDao.load(ckdept);
				Menu_Dept md = new Menu_Dept();
				md.setDept(d);
				md.setMenu(m);
				menuDeptDao.save(md);
				role.getMenuDepts().add(md);
			}
		}
	}
}
